<template>
  <!-- 城市列表 -->
  <div>
    <van-nav-bar left-arrow @click-left="$router.go(-1)" class="header">
      <template #title>
        <p>城市列表</p>
      </template>
    </van-nav-bar>
    <van-index-bar :index-list="indexList" :sticky-offset-top="num" v-if="flag">
      <van-index-anchor :index="item" v-for="item in indexList" :key="item"
        >{{ item }}
        <van-cell
          :title="list"
          v-for="list in AZlist[item]"
          :key="list"
          @click="selectCity"
        />
      </van-index-anchor>
    </van-index-bar>
    <p class="toLoad" v-else>加载中，请稍等...</p>
  </div>
</template>

<script>
import { getCity, getHotCity } from '@/api/city'
import { mapState } from 'vuex'
export default {
  name: 'City-page',
  data () {
    return {
      indexList: [
        '#',
        '热',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'j',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ],
      num: Number(50),
      AZlist: {},
      flag: false,
      body: ''
    }
  },
  async created () {
    const { body } = await getCity(1)
    this.body = body
    console.log(this.body)
    this.indexList.forEach(async item => {
      const newarr = []
      body.forEach(list => {
        if (item === list.short[0].toUpperCase()) {
          newarr.push(list.label)
        }
      })
      this.AZlist[item] = newarr
      // 设置当前城市
      if (item === '#') {
        this.AZlist[item].push(this.cityName)
        console.log(this.AZlist[item])
        console.log(body)
      }
      if (item === '热') {
        const hot = await getHotCity()
        hot.body.forEach(list => {
          const a = list.label
          this.AZlist[item].push(a)
          this.flag = true
        })
      }
      if (!this.AZlist[item][0]) {
        this.AZlist[item].push('暂无城市')
      }
    })
  },
  methods: {
    selectCity (e) {
      console.log(e.target.outerText)
      const city = e.target.outerText
      this.$store.commit('user/setCityName', city)
      const newCity = this.body.find(item => (item.label === city))
      console.log(newCity)
      this.$store.commit('user/setCityId', newCity.value)
      this.$router.go(-1)
    }
  },
  computed: {
    ...mapState('user', ['cityName'])
  }
}
</script>

<style scoped lang="less">
.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 100;
}
.box {
  height: 50px;
  width: 100%;
}
.toLoad {
  position: absolute;
  top: 45%;
  left: 30%;
}
/deep/ .van-index-bar__index {
  margin-top: 8px;
}
/deep/ .van-index-bar {
  margin-top: 50px;
}
/deep/ .van-index-bar__sidebar {
  margin-top: 20px;
}
</style>
